import { createApi, encrypt } from "@halobear/vue";
import { notification } from "ant-design-vue";
import authority from "./authority";
const key = "1e249ab537d2e4cc0d31b9227bfd785e";

const request = createApi({
  toast: message => notification.open({ message }), // 自定义提示
  setHeaders: config => {
    const { token } = authority.get() || {};
    const { params = {}, data = {} } = config;
    const now = Date.parse(new Date()) / 1000;
    const headers = {
      "X-Halo-App": "merchant-dashboard",
      "X-Http-Request-Halo-Sign": encrypt(
        { ...params, ...data, time: now },
        key
      )
    };
    if (token) {
      headers.Authorization = `Bearer ${token}`;
    }
    return headers;
  },
  loginForce() {
    authority.clear();
    window.location.reload();
  },
  createOptions: {
    withCredentials: false
  }
});

export default (...args) => {
  const [options = {}] = args;
  if (options.params) {
    if (!options.params.sort) {
      delete options.params.sort;
    }
    if (!options.params.order) {
      delete options.params.order;
    }
    if (!options.params.field) {
      delete options.params.field;
    }
  }
  return request(...args);
};
